import { defineStore } from "pinia";
import { getCompanyList as getCompanyListApi } from "@/apis/index.client";

interface Company {
  id: number;
  enterpriseName?: string;
  name?: string;
  enterpriseIndustry: string;
  region: string;
  industrialProductName: string;
  industrialProductCategory: string;
  subIndustry: string;
  typeTag?: number;
  longitude: number;
  latitude: number;
}
/**
 * 1是公司，2是项目，3是资源，4是建筑
 */
export enum GraphType {
  COMPANY = "emp",
  PROJECT = "project",
  RESOURCE = "resource",
  SCOPE = "scope",
}

export interface CompanyState {
  company: Partial<{
    emp: Company[];
    project: Company[];
    resource: Company[];
    scope: Company[];
  }>;
  graphType: null | GraphType;
}

export const useCompanyStore = defineStore("company", {
  state: (): CompanyState => ({
    company: {
      emp: [], // 企业
      project: [], // 项目
      resource: [], // 资源
      scope: [], // 建筑
    },
    graphType: null,
  }),
  actions: {
    async getCompanyList() {
      const data = await getCompanyListApi();
      this.company = data;
    },
  },
  getters: {
    companyList: (state) => {
      return Object.keys(state.company).reduce<any[]>((acc, key) => {
        const item = (state.company[key as keyof CompanyState["company"]] as any[]).map((item) => ({
          ...item,
          __key: key,
          name: key === "emp" ? item.enterpriseName : item.name,
        }));
        if (state.graphType) {
          state.graphType === key && acc.push(...item);
        } else {
          acc.push(...item);
        }
        return acc;
      }, []);
    },
  },
});
